package com.dousb.cloudlibrary.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dousb.cloudlibrary.common.BaseResponse;
import com.dousb.cloudlibrary.common.DeleteRequest;
import com.dousb.cloudlibrary.common.ErrorCode;
import com.dousb.cloudlibrary.common.ResultUtils;
import com.dousb.cloudlibrary.exception.BusinessException;
import com.dousb.cloudlibrary.exception.ThrowUtils;
import com.dousb.cloudlibrary.model.dto.comment.CommentAddRequest;
import com.dousb.cloudlibrary.model.dto.comment.CommentQueryRequest;
import com.dousb.cloudlibrary.model.dto.comment.LikeCountRequest;
import com.dousb.cloudlibrary.model.entity.Comment;
import com.dousb.cloudlibrary.model.entity.User;
import com.dousb.cloudlibrary.model.vo.CommentVO;
import com.dousb.cloudlibrary.service.CommentService;
import com.dousb.cloudlibrary.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 评论表接口
 */
@RestController
@RequestMapping("/comment")
@Slf4j
public class CommentController {

    @Resource
    private CommentService commentService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建评论表
     *
     * @param commentAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addComment(@RequestBody CommentAddRequest commentAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(commentAddRequest == null, ErrorCode.PARAMS_ERROR);
        //   在此处将实体类和 DTO 进行转换
        Comment comment = new Comment();
        BeanUtils.copyProperties(commentAddRequest, comment);
        // 数据校验
        commentService.validComment(comment, true);
        //   填充默认值
        User loginUser = userService.getLoginUser(request);
        comment.setUser_id(loginUser.getId());
        //处理是子评论还是父评论
        Long parentId = commentAddRequest.getParent_id();
        if (parentId == null) {
            comment.setParent_id(0L);
        } else {
            Comment parentComment = commentService.getById(parentId);
            if (parentComment != null) {
                Long rootId = parentComment.getRoot_id();
                if (rootId == null || rootId <= 0) {
                    comment.setRoot_id(parentId);
                } else {
                    comment.setRoot_id(rootId);
                }
            } else {
                comment.setRoot_id(0L);
                comment.setParent_id(0L);
            }
        }
        // 写入数据库
        boolean result = commentService.save(comment);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        //更新父评论的回复数量
        if (parentId != null && parentId != 0) {
            commentService.lambdaUpdate()
                    .setSql("reply_count = reply_count + 1")
                    .eq(Comment::getId, parentId)
                    .update();
        }
        // 返回新写入的数据 id
        long newCommentId = comment.getId();
        return ResultUtils.success(newCommentId);
    }

    /**
     * 删除评论表
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteComment(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Comment oldComment = commentService.getById(id);
        ThrowUtils.throwIf(oldComment == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldComment.getUser_id().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = commentService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


    /**
     * 根据 id 获取评论表（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<CommentVO> getCommentVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Comment comment = commentService.getById(id);
        ThrowUtils.throwIf(comment == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(commentService.getCommentVO(comment, request));
    }

    /**
     * 分页获取评论表列表（封装类）
     *
     * @param commentQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<CommentVO>> listCommentVOByPage(@RequestBody CommentQueryRequest commentQueryRequest,
                                                             HttpServletRequest request) {
        long current = commentQueryRequest.getCurrent();
        long size = commentQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Comment> commentPage = commentService.page(new Page<>(current, size),
                commentService.getQueryWrapper(commentQueryRequest));
        // 获取封装类
        return ResultUtils.success(commentService.getCommentVOPage(commentPage, request));
    }

    /**
     * 获取树形评论结构
     *
     * @param topicId    主题ID
     * @param topic_type 主题类型
     * @param request
     * @return
     */
    @GetMapping("/tree")
    public BaseResponse<List<CommentVO>> getCommentTree(
            @RequestParam Long topic_id,
            @RequestParam String topic_type,
            HttpServletRequest request) {

        ThrowUtils.throwIf(topic_id == null || topic_id <= 0, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(StrUtil.isBlank(topic_type), ErrorCode.PARAMS_ERROR);

        List<CommentVO> commentTree = commentService.getCommentTreeOptimized(topic_id, topic_type, request);
        return ResultUtils.success(commentTree);
    }

    /**
     * 分页获取当前登录用户创建的评论表列表
     *
     * @param commentQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<CommentVO>> listMyCommentVOByPage(@RequestBody CommentQueryRequest commentQueryRequest,
                                                               HttpServletRequest request) {
        ThrowUtils.throwIf(commentQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        commentQueryRequest.setUser_id(loginUser.getId());
        long current = commentQueryRequest.getCurrent();
        long size = commentQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Comment> commentPage = commentService.page(new Page<>(current, size),
                commentService.getQueryWrapper(commentQueryRequest));
        // 获取封装类
        return ResultUtils.success(commentService.getCommentVOPage(commentPage, request));
    }

    /**
     * 点赞
     *
     * @param likeCountRequest
     * @return BaseResponse<Integer>
     * @author 豆沙包
     * @date 2025/10/14 15:09
     */
    @PostMapping("/like/count")
    public BaseResponse<Integer> getLikeCount(@RequestBody LikeCountRequest likeCountRequest, HttpServletRequest request) {
        Long commentId = likeCountRequest.getCommentId();
        ThrowUtils.throwIf(commentId == null || commentId <= 0, ErrorCode.PARAMS_ERROR);
        try {
            commentService.lambdaUpdate()
                    .setSql("like_count = like_count + 1")
                    .eq(Comment::getId, commentId)
                    .update();
        } catch (Exception e) {
            log.error("like error", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "点赞失败");
        }
        return ResultUtils.success(commentService.getById(commentId).getLike_count());
    }
    // endregion
}
